﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

namespace FusionDotNet
{
    /// <summary>
    /// Create a new Google Fusion Table.
    /// </summary>
    public class CreateTableCommand : PostCommand<ScalarResult<int>>
    {
        /// <summary>
        /// Default Constructor. 
        /// </summary>
        /// <param name="tableSchema">DataTable used to infer the schema of the table to create.</param>
        /// <remarks>
        /// The TableName property of the DataTable provided may not be NULL or empty. The DataTable must have one or more columns.
        /// </remarks>
        public CreateTableCommand(DataTable tableSchema)
        {
            BuildDeleteString(tableSchema);
        }

        private void BuildDeleteString(DataTable tableSchema)
        {
            tableSchema
                .TableNotNull()
                .TableHasName()
                .TableHasColumns();

            List<string> columns = new List<string>();

            foreach (DataColumn column in tableSchema.Columns)
            {
                columns.Add(string.Format("'{0}' : {1}", column.ColumnName, TableBuilder.ConvertFromType(column.DataType)));
            }

            StringBuilder builder = new StringBuilder();
            builder.Append("sql=");
            builder.AppendFormat("CREATE TABLE {0} ({1})", tableSchema.TableName, String.Join(",", columns));

            Encoding encoding = GetContentEncoding();
            PostContent = encoding.GetBytes(builder.ToString());
        }

        /// <summary>
        /// Creates a ScalarResult based on the results of the command. The Result property contains the ID of the table created.
        /// </summary>
        /// <param name="reader">StreamReader containing the results of the operation.</param>
        /// <returns><see cref="ScalarResult&lt;TResult&gt;"/></returns>
        internal override ScalarResult<int> CreateResult(System.IO.StreamReader reader)
        {
            string header = reader.ReadLine();
            var result = new ScalarResult<int>();
            if (header == Constants.FUSION_TABLEID)
            {
                result.Success = true;
                string tableId = reader.ReadLine();
                result.Result = Int32.Parse(tableId);
            }
            else
            {
                result.Success = false;
            }
            return result;
        }
    }
}
